<!-- 倒计时的时间设置组件 -->
<template>
    <div>

        <el-form  label-position="left"
        label-width="100px" :model="form" style="width: 90%; margin: 0 auto;">
            <el-form-item label="窗口大小：">
                <el-slider v-model="form.windowSize" :min="200" :max="2000"></el-slider>
            </el-form-item>
            <el-form-item label="计时设置：">
                <el-row style="width: 100%;">
                    <el-col :span="12" style="text-align: center;">
                        分：<el-input-number style="width: 60%;" v-model="minute" controls-position="right" :min="0" :max="59" size="mini"/>
                    </el-col>
                    <el-col :span="12" style="text-align: center;">
                        秒：<el-input-number style="width: 60%;"  v-model="second" controls-position="right" :min="0" :max="59" size="mini"/>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="自动重置：">     
                <el-radio v-model="isAutonReset" :label="true">是</el-radio>
                <el-radio v-model="isAutonReset" :label="false">否</el-radio>
            </el-form-item>
            <el-form-item label="颜色设置：">            
                <el-radio v-model="fontColorStatus" label="white">纯 白</el-radio>
                <el-radio v-model="fontColorStatus" label="black">纯 黑</el-radio>
                <el-radio v-model="fontColorStatus" label="1" style="vertical-align: middle;">
                    自定义 <el-color-picker v-model="fontColor" show-alpha size="mini" style="vertical-align: middle;"></el-color-picker>
                </el-radio>
            </el-form-item>
            <el-form-item label="铃声设置：">
                <el-button  size="mini" @click="openAlarmDetailDalog()">查 看</el-button>
                <el-button type="primary" @click="openAlarmAddDalog()" size="mini" plain>新 增</el-button>
            </el-form-item>
            <el-form-item label="备选铃声：">
                <el-button  size="mini" @click="openPromptToneDialog()">查 看</el-button>
                <el-button type="primary" @click="uploadMp3()" size="mini" plain>上 传</el-button>
            </el-form-item>
            <el-form-item style="display: flex; justify-content: right;">
                <el-button @click="cancel()" size="mini">取 消</el-button>
                <el-button type="primary" @click="ensure()" size="mini">确 定</el-button>
            </el-form-item>
        </el-form>

        <audio id="myAudio" controls style="display: none;">
            <source id="mp3Source" src="" type="audio/mpeg">
        </audio>

        <!-- 提示音查看窗口 -->
        <el-dialog :fullscreen="true" :show-close="false" :modal="false" :visible.sync="dialogPromptToneTableVisible">
            <el-table
                ref="multipleTable"
                :data="promptToneTable"
                style="width: 100%;"
                height="200"
                @selection-change="handlePromptToneSelectionChange">
                <el-table-column type="selection" width="55" label="全选"></el-table-column> 
                <el-table-column prop="promptTone" label="提示音"></el-table-column>    
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button @click="playPromptTone(scope.row)" v-if="scope.row.status === 1" icon="el-icon-video-play" type="primary" circle size="mini"></el-button>
                        <el-button @click="pausePromptTone(scope.row)" v-else icon="el-icon-video-pause" type="warning" circle size="mini"></el-button>
                        <el-button @click="deletePromptTone(scope.row, 1)" icon="el-icon-delete" type="danger" circle size="mini"></el-button>
                    </template>
                </el-table-column>             
            </el-table>
            <div slot="footer" class="dialog-footer">                
                <el-button @click="dialogPromptToneTableVisible = false" size="mini">返 回</el-button>
                <el-button type="danger" @click="batchDeletePromptTone()" size="mini" :disabled="isAblePromptTone">删 除</el-button>
            </div>
        </el-dialog>

        <!-- 闹铃新增窗口 -->
        <el-dialog :fullscreen="true" :show-close="false" :modal="false" :visible.sync="dialogAlarmDddVisible">
            <el-form :model="form" size="mini">
                <el-form-item label="计时设置：">
                    <el-row style="width: 100%;">
                        <el-col :span="8" style="text-align: center;">
                            分：<el-input-number style="width: 60%;" v-model="alarmInfo.minute" controls-position="right" :min="0" :max="59" size="mini"/>
                        </el-col>
                        <el-col :span="8" style="text-align: center;">
                            秒：<el-input-number style="width: 60%;"  v-model="alarmInfo.second" controls-position="right" :min="0" :max="59" size="mini"/>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="选择闹铃：">
                    <el-select v-model="alarmInfo.fileResolve" placeholder="请选择">
                        <el-option
                        v-for="(item, index) in filesInfo"
                            :key="index"                                                
                            :label="item.fileName"
                            :value="item.fileResolve">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAlarmDddVisible = false" size="mini">返 回</el-button>
                <el-button type="primary" @click="addANewAlarm()" size="mini">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 闹铃查看窗口 -->
        <el-dialog :fullscreen="true" :show-close="false" :modal="false" :visible.sync="dialogAlarmDetailVisible">
            <el-table
                ref="multipleTable"
                :data="alarmsInfo"
                style="width: 100%;"
                height="200"
                @selection-change="handleAlarmSelectionChange">
                <el-table-column type="selection" width="55" label="全选"></el-table-column> 
                <el-table-column label="计时">
                    <template slot-scope="scope">
                        {{ scope.row.minute < 10 ? '0' + scope.row.minute : scope.row.minute}} : 
                        {{ scope.row.second < 10 ? '0' + scope.row.second : scope.row.second}}
                    </template>
                </el-table-column>    
                <el-table-column prop="fileName" label="提示音"></el-table-column>  
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button @click="deleteAlarm(scope.row, 1)" icon="el-icon-delete" type="danger" circle size="mini"></el-button>
                    </template>
                </el-table-column>             
            </el-table>
            <div slot="footer" class="dialog-footer">                
                <el-button @click="dialogAlarmDetailVisible = false" size="mini">返 回</el-button>
                <el-button type="danger" @click="batchDeleteAlarm()" size="mini" :disabled="isAbleAlarmsInfo">删 除</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { saveTimeInfo, readTimeInfo, readWindowSizeInfo, saveWindowSizeInfo, readAlramsInfo, saveAlramsInfo, readThemeColor, saveThemeColor, saveResetStatus } from '../../shared/utils/storage.js'
export default {
    data() {
        return {
            minute: 0,
            second: 0,
            isAutonReset: true,         // 倒计时结束是否自动重置时间
            fontColorStatus: 'white',    // 文字颜色状态
            fontColor: '',           // 文字颜色
            form: {
                windowSize: 400      // 窗口大小
            },
            dialogPromptToneTableVisible: false,
            selectedPromptTone: [],  // 被选中的提示音
            isAblePromptTone: true,  
            promptToneTable: [],     // 提示音表格
            dialogAlarmDddVisible: false,
            filesInfo: [],           // 存储文件名称和文件的绝对路径，用来单选
            alarmInfo: {
                minute: 0,
                second: 0,
                fileName: '',
                fileResolve: ''
            },                       // 闹铃信息
            dialogAlarmDetailVisible: false,
            selectedAlarmsInfo: [],  // 被选中的闹铃信息
            isAbleAlarmsInfo: true,
            alarmsInfo: []           // 闹铃信息，包括闹铃的时间、文件名称和文件的绝对路径
        }
    },
    async created() {
        const form = readTimeInfo()
        this.minute = form.minute
        this.second = form.second
        this.form.windowSize = readWindowSizeInfo()
        const color = readThemeColor()
        if (color != 'white' && color != 'black') {
            this.fontColorStatus = '1'
            this.fontColor = color
        } else {
            this.fontColorStatus = color
        }
    },
    methods: {
        // 校验分钟和秒钟是否都是数字格式
        verfiyIsInteger(minute, second) {
            return Number.isInteger(minute) && Number.isInteger(second)
        },
        // 处理提示音对话框中的选择改变情况
        handlePromptToneSelectionChange(value) {
            this.selectedPromptTone  = value
            if (value.length > 0) {
                this.isAblePromptTone = false
            } else {
                this.isAblePromptTone = true
            }
        },
        // 处理闹铃对话框中的选择改变情况
        handleAlarmSelectionChange(value) {
            this.selectedAlarmsInfo = value
            if (value.length > 0) {
                this.isAbleAlarmsInfo = false
            } else {
                this.isAbleAlarmsInfo = true
            }
        },
        // 打开提示音对话框
        async openPromptToneDialog() {
            this.promptToneTable = []
            const filesname = await window.myApi.getAllMp3FileName()
            const filesResolve = await window.myApi.getAllMp3FileResolve()
            for (let i = 0; i < filesname.length; i++) {
                this.promptToneTable.push({ 
                    promptTone: filesname[i],          // 文件名 
                    fileResolve: filesResolve[i],      // 文件绝对路径 
                    status: 1                          // 状态, 1代表未播放，2代表播放
                }) 
            }
            this.dialogPromptToneTableVisible = true
        },
        // 上传map3
        async uploadMp3() {
            const isUplaod = await window.myApi.uploadMp3()
            if (isUplaod) {
                this.$message({
                    type: "success",
                    message: "上传成功！"
                })
            }
        },
        // 播放提示音
        async playPromptTone(row) {
            for (let i = 0; i < this.promptToneTable.length; i++) {
                if (row.fileResolve === this.promptToneTable[i].fileResolve) {
                    this.promptToneTable[i].status = 2
                } else {
                    this.promptToneTable[i].status = 1
                }
            }
            var audioElement = document.getElementById("myAudio")
            var sourceElement = document.getElementById("mp3Source")

            const dataUrl = await window.myApi.readMp3FileToDataUrlByResolve(row.fileResolve)

            // 更改source元素的src属性（文件路径）
            sourceElement.src = dataUrl // 替换为实际的新路径
            // 刷新audio元素，使其重新加载新的音频资源
            audioElement.load()
            audioElement.play()

        },
        // 暂停提示音
        pausePromptTone(row) {
            console.log(row)
            var audioElement = document.getElementById("myAudio")
            audioElement.pause()
            for (let i = 0; i < this.promptToneTable.length; i++) {
                this.promptToneTable[i].status = 1
            }
            
        },
        // 删除一个提示音
        async deletePromptTone(row, status) {
            console.log(row)
            const isDeleted = await window.myApi.deleteMp3FileInDirectory(row.fileResolve)
            if (isDeleted && status === 1) {
                this.$message({
                    type: "success",
                    message: "操作成功！"
                })
            }
            this.openPromptToneDialog()
        },
        // 批量删除提示音
        async batchDeletePromptTone() {
            for (let i = 0; i < this.selectedPromptTone.length; i++) {
                this.deletePromptTone(this.selectedPromptTone[i], 0)
            }
            this.$message({
                type: "success",
                message: "操作成功！"
            })
        },
        // 打开闹铃新增对话框
        async openAlarmAddDalog() {
            this.filesInfo = []
            const filesname = await window.myApi.getAllMp3FileName()
            const filesResolve = await window.myApi.getAllMp3FileResolve()
            for (let i = 0; i < filesname.length; i++) {
                this.filesInfo.push({ 
                    fileName: filesname[i],             // 文件名 
                    fileResolve: filesResolve[i]        // 文件绝对路径 
                }) 
            }
            this.dialogAlarmDddVisible = true
        },
        // 新增一个闹铃
        addANewAlarm() {
            if (!this.verfiyIsInteger(this.alarmInfo.minute, this.alarmInfo.second)) {
                this.$message({
                    type: "error",
                    message: "请输入正确的时间！"                
                })
                return
            }
            if (this.verfiyAlarmIsRepeated(this.alarmInfo)) {
                this.$message({
                    type: "error",
                    message: "该时间点的闹铃已存在！"
                })
                return
            }
            if (this.alarmInfo.fileResolve === '') {
                this.$message({
                    type: "error",
                    message: "请选择提示音！"
                })
                return
            }
            for (let i = 0; i < this.filesInfo.length; i++) {
                if (this.filesInfo[i].fileResolve === this.alarmInfo.fileResolve) {
                    this.alarmInfo.fileName = this.filesInfo[i].fileName
                    break
                }
            }
            let alarmsInfo = readAlramsInfo()
            alarmsInfo.push(this.alarmInfo)
            saveAlramsInfo(alarmsInfo)
            this.$message({
                type: "success",
                message: "添加成功！"
            })
            this.dialogAlarmDddVisible = false
        },
        // 校验闹铃是否有重复的现象
        verfiyAlarmIsRepeated(alarm) {
            const alarmsInfo = readAlramsInfo()
            for (let i = 0; i < alarmsInfo.length; i++) {
                const alarmInfo = alarmsInfo[i]
                if (alarm.minute === alarmInfo.minute && alarm.second === alarmInfo.second) {
                    return true
                }
            }
            return false
        },
        // 打开闹铃查看对话框
        openAlarmDetailDalog() {
            this.alarmsInfo = readAlramsInfo()
            this.dialogAlarmDetailVisible = true
        },
        // 删除一个闹铃
        deleteAlarm(row, status) {
            for (let i = 0; i < this.alarmsInfo.length; i++) {
                const alarmInfo = this.alarmsInfo[i]
                if (row.minute === alarmInfo.minute && row.second === alarmInfo.second) {
                    this.alarmsInfo.splice(i, 1)
                    saveAlramsInfo(this.alarmsInfo)
                    this.openAlarmDetailDalog()
                    if (status === 1) {
                        this.$message({
                            type: "success",
                            message: "操作成功！"
                        })
                    }
                    return
                }
            }
        },
        // 批量删除闹铃
        batchDeleteAlarm() {
            for (let i = 0; i < this.selectedAlarmsInfo.length; i++) {
                this.deleteAlarm(this.selectedAlarmsInfo[i], 0)
            }
            this.$message({
                type: "success",
                message: "操作成功！"
            })
        },
        // 取消
        cancel() {
            window.myApi.closeNewWindow(1)
        },
        // 确定
        ensure() {
            if (!this.verfiyIsInteger(this.minute, this.second)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的时间！'
                })
                return
            }
            let form = {
                minute: this.minute,
                second: this.second
            }
            saveTimeInfo(form)
            saveResetStatus(this.isAutonReset)
            saveWindowSizeInfo(this.form.windowSize)
            if (this.fontColorStatus === '1') {
                saveThemeColor(this.fontColor)
            } else {
                saveThemeColor(this.fontColorStatus)
            }
            window.myApi.saveWindowSize(this.form.windowSize)
            window.myApi.closeNewWindow(2)
        }
    }
}
</script>